package com.sahala.redis.util;

import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.Closeable;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

public class RedisUtil {

	public static byte[] getBytesFromObject(Object obj) {
		ObjectOutputStream os = null;
		byte[] sendBuf = null;
		ByteArrayOutputStream byteStream = null;
		try {
			byteStream = new ByteArrayOutputStream(5000);
			os = new ObjectOutputStream(new BufferedOutputStream(byteStream));
			os.flush();
			os.writeObject(obj);
			os.flush();
			sendBuf = byteStream.toByteArray();
		} catch (Exception e) {

		} finally {
			closeIfCan(os);
			closeIfCan(byteStream);
		}
		return sendBuf;
	}

	private static void closeIfCan(Closeable able) {
		try {
			able.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public static Object getObjectFromBytes(byte[] bytes) {
		Object obj = null;
		ByteArrayInputStream bi = null;
		ObjectInputStream oi = null;
		try {
			bi = new ByteArrayInputStream(bytes);
			oi = new ObjectInputStream(bi);
			obj = oi.readObject();
		} catch (Exception e) {
			System.out.println("translation" + e.getMessage());
			e.printStackTrace();
		} finally {
			closeIfCan(bi);
			closeIfCan(oi);
		}
		return obj;
	}
}
